package drds.configuration.mvc.util.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

public class SqlForbiddenFilter implements Filter {
    private static boolean SQLInjectionValidate(String string) {
        string = string.toLowerCase();
        // 最后这javascript alert session
        // cookie都是为了防止xss漏洞攻击,这个use,update不能加入到上述列表,因为有链接地址中包含是use/update
        final String bad = "exec,execute,insert,create,drop,table,from,grant,group_concat,column_name,"
                + "information_schema.columns,information_schema,columns,table_schema,union,where,select,delete,order,by,count,*,"
                + "chr,mid,master,truncate,char,declare,or,like,1=1,javascript,cookie,session,../";
        String[] badArray = bad.split(",");
        for (int i = 0; i < badArray.length; i++) {
            if (string.indexOf(badArray[i]) != -1) {
                return true;
            }
        }
        return false;
    }

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @SuppressWarnings("static-access")
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        // false:表示不符合条件
        boolean flag = false;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        Enumeration<?> params = request.getParameterNames();
        // 表示不符合管理员要求还需继续检测
        while (params.hasMoreElements()) {
            String name = params.nextElement().toString();
            String[] value = request.getParameterValues(name);
            for (int i = 0; i < value.length; i++) {
                if (SQLInjectionValidate(value[i]) == true) {
                    flag = true;
                    break;
                }
            }
        }
        if (flag) {
            try {
                (response).sendError(response.SC_FORBIDDEN, "");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void destroy() {

    }


}
